import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import cv2

class MainWindow:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("视频流客户端")
        self.setup_gui()
        self.current_camera = None

    def setup_gui(self):
        """设置GUI界面"""
        # 主布局：左侧控制区，右侧视频显示区
        main_frame = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 左侧控制区
        control_frame = ttk.Frame(main_frame)
        main_frame.add(control_frame)

        # 连接控制
        conn_frame = ttk.LabelFrame(control_frame, text="连接控制")
        conn_frame.pack(padx=5, pady=5, fill="x")
        
        self.connect_btn = ttk.Button(conn_frame, text="连接服务器")
        self.connect_btn.pack(pady=5, padx=5)

        # 摄像头列表
        camera_frame = ttk.LabelFrame(control_frame, text="已连接摄像头")
        camera_frame.pack(padx=5, pady=5, fill="both", expand=True)

        # 创建摄像头列表
        self.camera_list = ttk.Treeview(camera_frame, columns=("ip",), 
                                      show="headings", height=6)
        self.camera_list.heading("ip", text="设备地址")
        self.camera_list.pack(pady=5, padx=5, fill="both", expand=True)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(camera_frame, orient="vertical", 
                                command=self.camera_list.yview)
        scrollbar.pack(side="right", fill="y")
        self.camera_list.configure(yscrollcommand=scrollbar.set)

        # 绑定选择事件
        self.camera_list.bind('<<TreeviewSelect>>', self.on_camera_selected)

        # 右侧视频显示区
        video_frame = ttk.Frame(main_frame)
        main_frame.add(video_frame)

        # 视频显示
        self.video_label = ttk.Label(video_frame)
        self.video_label.pack(padx=5, pady=5, expand=True)

        # 状态栏
        self.status_var = tk.StringVar(value="未连接")
        status_label = ttk.Label(self.root, textvariable=self.status_var, 
                               relief=tk.SUNKEN)
        status_label.pack(fill="x", padx=5, pady=2)

    def update_frame(self, frame):
        """更新视频帧"""
        if frame is not None:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            # 调整图像大小以适应显示区域
            height, width = frame.shape[:2]
            max_height = 480  # 最大显示高度
            if height > max_height:
                scale = max_height / height
                width = int(width * scale)
                height = max_height
                frame = cv2.resize(frame, (width, height))
            
            image = Image.fromarray(frame)
            photo = ImageTk.PhotoImage(image=image)
            self.video_label.configure(image=photo)
            self.video_label.image = photo

    def add_camera(self, camera_id, ip_address):
        """添加新的摄像头到列表"""
        self.camera_list.insert("", "end", iid=camera_id, values=(ip_address,))

    def remove_camera(self, camera_id):
        """从列表中移除摄像头"""
        self.camera_list.delete(camera_id)

    def on_camera_selected(self, event):
        """处理摄像头选择事件"""
        selection = self.camera_list.selection()
        if selection:
            camera_id = selection[0]
            self.current_camera = camera_id
            if hasattr(self, 'camera_select_callback'):
                self.camera_select_callback(camera_id)

    def set_connect_callback(self, callback):
        """设置连接按钮的回调函数"""
        self.connect_btn.configure(command=callback)

    def set_camera_select_callback(self, callback):
        """设置摄像头选择的回调函数"""
        self.camera_select_callback = callback

    def update_status(self, status):
        """更新状态栏"""
        self.status_var.set(status)

    def run(self):
        """运行GUI"""
        self.root.minsize(800, 600)
        self.root.mainloop() 